import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { ModalForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-form';
import { User, addUser } from '@/services/ant-design-pro/api';
import { Button, message } from 'antd';

// 新增编辑- 提交
const handleAdd = async (fields: API.UserListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addUser({ ...fields });
    hide();
    return true;
  } catch (error) {
    hide();
    message.error('添加失败，请重试！');
    return false;
  }
};

const TableList: React.FC = () => {
  // 新增编辑弹窗 - 函数式状态
  const [UserVisible, setUserVisibleChange] = useState(false);
  const [UserType, setUserTypeChange] = useState<string>('add');
  const userRestFormRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();

  // const [currentRow, setCurrentRow] = useState<API.UserListItem>();

  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 17 },
  };

  const columns: ProColumns<API.UserListItem>[] = [
    {
      title: '用户ID',
      dataIndex: 'user_id',
      tip: '测试tip',
    },
    {
      title: '用户名称',
      dataIndex: 'name',
    },
    {
      title: '用户账号',
      dataIndex: 'username',
    },
    {
      title: '手机号',
      dataIndex: 'iphone',
    },

    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '异常',
          status: 'Error',
        },
        1: {
          text: '正常',
          status: 'Success',
        },
      },
    },

    {
      title: '创建时间',
      dataIndex: 'createdAt',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        const disable =
          record.status === 1 ? (
            <a
              key="config"
              onClick={() => {
                console.log(record);
              }}
            >
              启用
            </a>
          ) : (
            <a
              key="config"
              onClick={() => {
                console.log(record);
              }}
            >
              禁用
            </a>
          );

        const edit = [
          <a
            key="config"
            onClick={() => {
              setUserTypeChange('edit');
              setUserVisibleChange(true);
              console.log(record);
              userRestFormRef?.current?.setFieldsValue({
                name: record.name,
                username: record.username,
                iphone: record.iphone,
                desc: record.desc,
              });
            }}
          >
            编辑
          </a>,
          disable,
        ];
        return edit;
      },
    },
  ];

  return (
    <PageContainer title="用户管理">
      {/* Table列表 */}
      <ProTable<API.UserListItem, API.PageParams>
        headerTitle="用户管理列表"
        actionRef={actionRef}
        rowKey="key"
        options={{ fullScreen: true, reload: true, setting: true }}
        search={{ labelWidth: 120 }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setUserTypeChange('add');
              userRestFormRef.current?.resetFields();
              setUserVisibleChange(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={User}
        columns={columns}
        // rowSelection={{
        //   onChange:(_,selectedRows)=>{
        //     console.log('selectedRows',selectedRows);

        //   }
        // }}
      />

      {/* 新建编辑 弹窗界面 */}
      <ModalForm
        formRef={userRestFormRef}
        title={UserType === 'add' ? '新建用户' : '编辑用户'}
        width="500px"
        visible={UserVisible}
        onVisibleChange={setUserVisibleChange}
        {...formItemLayout}
        layout="horizontal"
        // submitter={{
        //   searchConfig: {
        //     resetText: '重置',
        //   },
        //   resetButtonProps: {
        //     onClick: () => {
        //       userRestFormRef.current?.resetFields();
        //       //   setModalVisible(false);
        //     },
        //   },
        // }}
        onFinish={async (value) => {
          console.log(value);

          const success = await handleAdd(value as API.UserListItem);
          if (success) {
            setUserVisibleChange(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            userRestFormRef.current?.resetFields();
          }
          return true;
        }}
      >
        {/* Form 表单 */}
        <ProFormText
          label="用户账号"
          rules={[
            {
              required: true,
              message: '用户账号为必填项',
            },
          ]}
          width="md"
          name="username"
        />
        <ProFormText
          label="用户名称"
          rules={[
            {
              required: true,
              message: '用户名称为必填项',
            },
          ]}
          width="md"
          name="name"
        />
        <ProFormText
          label="手机号  "
          rules={[
            {
              required: true,
              message: '手机号为必填项',
            },
          ]}
          width="md"
          name="iphone"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '角色分配为必填项',
            },
          ]}
          options={[
            {
              value: 'role1',
              label: '角色1',
            },
          ]}
          width="md"
          name="role"
          label={`角色分配`}
        />
        <ProFormTextArea label="用户介绍" width="md" name="desc" />
      </ModalForm>
    </PageContainer>
  );
};

export default TableList;
